package com.example.project3;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.project3.adapter.BookAdapter;
import com.example.project3.database.BookDatabaseHelper;
import com.example.project3.model.Book;
import com.google.android.material.textfield.TextInputEditText;
import java.util.List;

/**
 * 书籍管理页面
 * 实现书籍的增删改查功能
 */
public class BookManagementActivity extends AppCompatActivity implements BookAdapter.OnBookActionListener {

    // UI控件
    private TextInputEditText etBookNumber;
    private TextInputEditText etBookName;
    private Button btnAdd;
    private Button btnQuery;
    private Button btnClear;
    private RecyclerView recyclerViewBooks;
    private SwipeRefreshLayout swipeRefreshLayout;

    // 数据相关
    private BookAdapter bookAdapter;
    private BookDatabaseHelper databaseHelper;
    private String currentUserEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_management);

        // 初始化视图
        initViews();
        
        // 初始化数据
        initData();
        
        // 设置监听器
        setListeners();
        
        // 加载书籍列表
        loadAllBooks();
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        etBookNumber = findViewById(R.id.et_book_number);
        etBookName = findViewById(R.id.et_book_name);
        btnAdd = findViewById(R.id.btn_add);
        btnQuery = findViewById(R.id.btn_query);
        btnClear = findViewById(R.id.btn_clear);
        recyclerViewBooks = findViewById(R.id.recycler_view_books);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);

        // 设置ActionBar标题和返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.book_management);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 初始化RecyclerView
        recyclerViewBooks.setLayoutManager(new LinearLayoutManager(this));
        bookAdapter = new BookAdapter();
        bookAdapter.setOnBookActionListener(this);
        recyclerViewBooks.setAdapter(bookAdapter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        databaseHelper = new BookDatabaseHelper(this);
        
        // 获取当前登录用户邮箱
        SharedPreferences sp = getSharedPreferences("user_info", 0);
        currentUserEmail = sp.getString("email", "");
        
        if (currentUserEmail.isEmpty()) {
            Toast.makeText(this, "用户信息异常，请重新登录", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * 设置监听器
     */
    private void setListeners() {
        // 添加按钮
        btnAdd.setOnClickListener(v -> showAddBookDialog());
        
        // 查询按钮
        btnQuery.setOnClickListener(v -> queryBooks());
        
        // 清空按钮
        btnClear.setOnClickListener(v -> clearInputs());
        
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadAllBooks);
    }

    /**
     * 显示添加书籍对话框
     */
    private void showAddBookDialog() {
        showBookDialog(null, -1, "添加书籍");
    }

    /**
     * 显示书籍编辑/添加对话框
     */
    private void showBookDialog(Book book, int position, String title) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_book, null);
        
        EditText etDialogBookNumber = dialogView.findViewById(R.id.et_dialog_book_number);
        EditText etDialogBookName = dialogView.findViewById(R.id.et_dialog_book_name);
        EditText etDialogAuthor = dialogView.findViewById(R.id.et_dialog_author);
        EditText etDialogPrice = dialogView.findViewById(R.id.et_dialog_price);

        // 如果是编辑模式，填充原有数据
        if (book != null) {
            etDialogBookNumber.setText(book.getBookNumber());
            etDialogBookName.setText(book.getBookName());
            etDialogAuthor.setText(book.getAuthor());
            etDialogPrice.setText(String.valueOf(book.getPrice()));
        }

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(dialogView)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", null)
                .create();

        dialog.setOnShowListener(d -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                String bookNumber = etDialogBookNumber.getText().toString().trim();
                String bookName = etDialogBookName.getText().toString().trim();
                String author = etDialogAuthor.getText().toString().trim();
                String priceStr = etDialogPrice.getText().toString().trim();

                // 验证输入
                if (bookNumber.isEmpty()) {
                    etDialogBookNumber.setError("请输入书号");
                    return;
                }
                if (bookName.isEmpty()) {
                    etDialogBookName.setError("请输入书名");
                    return;
                }

                double price = 0.0;
                try {
                    if (!priceStr.isEmpty()) {
                        price = Double.parseDouble(priceStr);
                    }
                } catch (NumberFormatException e) {
                    etDialogPrice.setError("请输入正确的价格");
                    return;
                }

                if (book == null) {
                    // 添加新书籍
                    addBook(bookNumber, bookName, author, price);
                } else {
                    // 更新书籍
                    updateBook(book, bookNumber, bookName, author, price, position);
                }
                
                dialog.dismiss();
            });
        });

        dialog.show();
    }

    /**
     * 添加书籍
     */
    private void addBook(String bookNumber, String bookName, String author, double price) {
        Book newBook = new Book(bookNumber, bookName, author, price, currentUserEmail);
        long result = databaseHelper.addBook(newBook);
        
        if (result != -1) {
            newBook.setId((int) result);
            bookAdapter.addBook(newBook);
            Toast.makeText(this, "添加书籍成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "添加书籍失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新书籍
     */
    private void updateBook(Book book, String bookNumber, String bookName, String author, double price, int position) {
        book.setBookNumber(bookNumber);
        book.setBookName(bookName);
        book.setAuthor(author);
        book.setPrice(price);
        
        int result = databaseHelper.updateBook(book);
        if (result > 0) {
            bookAdapter.updateBook(position, book);
            Toast.makeText(this, "更新书籍成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "更新书籍失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 查询书籍
     */
    private void queryBooks() {
        String bookNumber = etBookNumber.getText().toString().trim();
        String bookName = etBookName.getText().toString().trim();
        
        List<Book> books;
        if (bookNumber.isEmpty() && bookName.isEmpty()) {
            // 空查询显示全部书籍
            books = databaseHelper.getAllBooks(currentUserEmail);
        } else {
            // 根据条件查询
            books = databaseHelper.searchBooks(currentUserEmail, bookNumber, bookName);
        }
        
        bookAdapter.updateBookList(books);
        Toast.makeText(this, "查询到 " + books.size() + " 本书籍", Toast.LENGTH_SHORT).show();
    }

    /**
     * 清空输入框
     */
    private void clearInputs() {
        etBookNumber.setText("");
        etBookName.setText("");
        etBookNumber.clearFocus();
        etBookName.clearFocus();
    }

    /**
     * 加载所有书籍
     */
    private void loadAllBooks() {
        swipeRefreshLayout.setRefreshing(true);
        List<Book> books = databaseHelper.getAllBooks(currentUserEmail);
        bookAdapter.updateBookList(books);
        swipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 编辑书籍回调
     */
    @Override
    public void onEditBook(Book book, int position) {
        showBookDialog(book, position, "编辑书籍");
    }

    /**
     * 删除书籍回调
     */
    @Override
    public void onDeleteBook(Book book, int position) {
        new AlertDialog.Builder(this)
                .setTitle("删除确认")
                .setMessage("确定要删除《" + book.getBookName() + "》吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    databaseHelper.deleteBook(book.getId(), currentUserEmail);
                    bookAdapter.removeBook(position);
                    Toast.makeText(this, "删除书籍成功", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 处理ActionBar的返回按钮
     */
    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}